package com.gitee.secretopen.sso.component;

import cn.chenc.framework.cache.util.RedisUtils;
import com.gitee.secretopen.sso.common.constant.Constants;
import com.gitee.secretopen.sso.db.pojo.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/3/3 15:28
 *
 */
@Component
public class TokenService {
    // 令牌自定义标识
    private static final String HEADER="Authorization";

    private static final String TOKEN_PREFIX="Bearer ";

    // 令牌有效期（默认30分钟）
    private static final int expireTime=30;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public User getAdminLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getAdminToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            // 解析对应的权限以及用户信息
            String userKey = getAdminTokenKey(token);
            User user = (User)redisUtils.get(userKey);
            return user;
        }
        return null;
    }


    /**
     * 设置用户身份信息
     */
    public void setLoginUser(String userKey,User user)
    {
        if (ObjectUtils.isNotEmpty(user) && StringUtils.isNotEmpty(userKey))
        {
            refreshToken(userKey,user);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String userKey)
    {
        if (StringUtils.isNotEmpty(userKey))
        {
            redisUtils.del(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param
     * @return 令牌
     */
    public String createToken()
    {
        String token = UUID.randomUUID().toString();

        return token;
    }


    /**
     * 刷新令牌有效期
     *
     * @param userKey redisKey
     */
    public void refreshToken(String userKey,User user)
    {
        // 刷新30分钟缓存
        redisUtils.set(userKey, user, expireTime, TimeUnit.MINUTES);
    }



    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getAdminToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(TOKEN_PREFIX))
        {
            token = token.replace(TOKEN_PREFIX, "");
        }
        return token;
    }

    public String getAdminTokenKey(String token) {
        return Constants.SSO_ADMIN_LOGIN_KEY + token;
    }

    public String getSsoTokenKey(String token) {
        return Constants.SSO_LOGIN_KEY + token;
    }
}
